import DeliverApi from '../../../common/api/breedsales/deliverbills.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
let _ownOrgs = [], _levelType = [], getMainMessage = [], getEntryInfo = [], _personOrg = [], _pickerTime
let _vm, saleOrgsinfo, _pigTypeList = []
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening">
<div class="toolbar-inner">
<span style='margin:0 auto;margin-top:10px'>请选择业务日期</span>
<a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a>
</div>
</div>`;

    $(function () {

        const _json = Utils.ParsingUrl(window.location);
        _vm = new Vue({
            el: "#addsaleorders-form",
            data() {
                return {
                    "bizDate": "",
                    "saleOrgId": "",
                    "saleOrgName": "",
                    "remark": "",
                    "entries": [],
                    "pigType": "",
                    uploadCount: 0,
                    images: [],///处理weui自带上传插件回显重新上传时的问题
                    datas: []
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        saleOrgs()
        _datetimePickerInit();
        _deliveryPickerInit();
        // _initCommand()
        clickFun()
    });

    // 初始化数据
    const _initCommand = async () => {
        //猪只类型
        await requestDict(DictionaryType.PIG_FIXEDPRICE_TYPE).then(res => {
            _pigTypeList = res.data;
            $('#pigType').empty().select2({
                placeholder: '请选择猪只类型...', //默认文字提示
                language: "zh-CN",//汉化
                data: res.data.map(item => {
                    return {
                        id: item.value,
                        text: item.displayName,
                    }
                })
            });
            $('#pigType').setSelectValue();
        });
        // 选择猪只类型 清除校验
        $('#pigType').on("select2:select", function () {
            _vm.pigType = $(this).select2('data')[0]?.id
        })
        //销售品类
        let type = await requestDict(DictionaryType.LEVEL_TYPE);
        _levelType = type.data;

        //查信息询登录用户拥有的组织
        let personOrgs = await DeliverApi.postUserOrgsList();
        personOrgs.forEach(item => {
            if (item.optTag == 1 && item.tags.indexOf('210') !== -1) {
                _personOrg.push(item.oId);
            }
        });

        // 赋值 销售组织 业务日期 备注
        let datas = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        // 不为空时 赋值
        if (Utils.IsNotNull(datas)) {
            // $('#businessTime').val(datas.bizDate);
            _vm.bizDate = datas.bizDate
            // _vm.saleOrgId = datas.saleOrgId
            // _vm.saleOrgName = datas.saleOrgName
            _vm.remark = datas.remark
            _vm.pigType = datas.pigType
            $('#pigType').val(datas.pigType).trigger('change');
            // $('#saleOrgId').setSelectValue(datas.saleOrgId, `${datas.saleOrgName}(${datas.saleOrgNumCode})`);
            $('#saleOrgId').setSelectValue(datas.saleOrgId);
        }

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            // 删除分录 删除页面数据 删除ID
            window.sessionStorage.removeItem("getEntryInfo");
            window.sessionStorage.removeItem("deliverDatas");
            window.sessionStorage.removeItem("ids");
            location.href = `../deliverbills/deliverbills.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            $("#informationSubmit").text("保存");
            $("title").text("销售出库单 - 编辑");
            // $('#selCustomerInfos').prop('disabled', true);
            // $("#saleOrgId").prop('disabled', true);
            DeliverApi.getDeliverinfo(ids).then(res => {
                _vm.bizDate = (res.bizFormObj.bizDate.split(' '))[0].replace(/\//g, '-')
                _vm.saleOrgId = res.saleOrgId
                _vm.saleOrgName = res.saleOrgName
                $('#saleOrgId').setSelectValue(res.saleOrg.id);
                _vm.pigType = res.pigType
                $('#pigType').val(res.pigType).trigger('change');
                // $('#remark').val(res.remark)
                _vm.remark = res.remark
                // 获取分录数据
                getEntryInfo = res.entries;
                // 存分录
                res.entries.forEach((item, index) => item.seq = index + 1)
                JSON.stringify(Utils.SetSessionStorage("getEntryInfo", { entries: getEntryInfo, breedPigEntries: res.breedPigEntries }))
                JSON.stringify(Utils.SetSessionStorage("ids", ids))
                $('#salesEntry').empty().append(addsaleTemplate(res.entries));
            });
        }

        // 获取分录信息
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        // 渲染 分录
        if (Utils.IsNotNull(getEntryInfo)) {
            $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo.entries));
        }
    }

    //业务日期控件初始化
    const _datetimePickerInit = () => {
        initCurrentDay()
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#search-date').on('click', function (e) {
            e.stopPropagation();
            $("#search-date").picker("open");
            _pickerDate();
        });
        $("#search-date").datetimePicker(
            {
                toolbarTemplate: toolbarTemplate,
                toolbarCloseText: "确定",
                toolbarCancelText: "取消",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },
                //确定选择时的操作
                onClose: function (picker) {
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2];
                    _pickerTime = '';
                    _pickerTime = value;
                }
            }
        );
    }

    //业务日期确认事件
    const _pickerDate = () => {
        $(document).on("click", ".close-picker", function () {
            $('#businessTime').val(_pickerTime);
            _vm.bizDate = _pickerTime
        });
    }
    // 业务日期获取当天
    const initCurrentDay = () => {
        let todayDate = moment().format('YYYY-MM-DD')
        $('#businessTime').val(todayDate)
        _vm.bizDate = todayDate
    }

    //发货日期控件初始化
    const _deliveryPickerInit = () => {
        initCurrentDay()
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        // 开始日期
        $('#delivery-date').on('click', function (e) {
            e.stopPropagation();
            $("#delivery-date").picker("open");
            _deliverypickerDate();
        });
    }

    // 初始化销售组织
    const saleOrgs = async () => {
        _ownOrgs = await DeliverApi.postUserOrgsList();
        DeliverApi.getOrgsListType().then(res => {
            let sale = res.filter(s => s.typeValue == true);
            let obj = _ownOrgs.filter(item => sale.some(item2 => item2.id == item.oId));
            $('#saleOrgId').select2({
                placeholder: '请选择销售组织...', //默认文字提示
                language: "zh-CN",//汉化
                data: obj.map(item => {
                    return {
                        id: item.oId,
                        name: item.oName,
                        numCode: item.oNumCode,
                        text: `${item.oName}(${item.oNumCode})`
                    }
                }),
            });
            $("#saleOrgId").setSelectValue();

            //解决字段过长
            $('#saleOrgId').on('change', function () {
                saleOrgsinfo = cutstr($('#select2-saleOrgId-container').text(), 22)
                $('#select2-saleOrgId-container').text(`${saleOrgsinfo}`)
                if (Utils.IsNotNull($('#saleOrgId').select2('data')[0])) {
                    _vm.saleOrgId = $('#saleOrgId').select2('data')[0].id
                    _vm.saleOrgName = $('#saleOrgId').select2('data')[0].name
                }
            });

            if (Utils.IsNotNull(getUrlKey("id"))) {
                $("#saleOrgId").setSelectValue(_vm.saleOrgId)
                $('#saleOrgId').prop('disabled', true);
            } else {
                $("#saleOrgId").change()
            }
        }).then(_ => {
            _initCommand()
        })
    }

    const storeSession = () => {
        let deliver = {
            "bizDate": _vm.bizDate,
            "saleOrgId": _vm.saleOrgId,
            "saleOrgName": $(`#saleOrgId`).select2('data')[0].name,
            "saleOrgNumCode": $(`#saleOrgId`).select2('data')[0].NumCode,
            "remark": _vm.remark,
            "pigType": _vm.pigType
        }
        // 保存数据内容
        Utils.SetRouterState('deliverDatas', deliver)
    }


    // 操作函数
    const clickFun = () => {
        // 点击分录
        $('#add-saleEntry').on("click", function (e) {
            if (!Utils.IsNotNull($('#saleOrgId').val())) {
                return $.toptip(`请先选择销售组织!`, 'warning');
            }
            if (!Utils.IsNotNull($('#pigType').val())) {
                return $.toptip(`请先选择猪只类型!`, 'warning');
            }
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.entries?.length || 0
            location.href = `../deliverbills/entry.html?v=${Utils.GetTime()}&orgId=${_vm.saleOrgId}&index=${index}&isEdit=${false}`;
        })

        // 提交数据~~
        $('#informationSubmit').on("click", function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
            if (!Utils.IsNotNull($(`#saleOrgId`).select2('data'))) {
                return $.toptip(`请选择销售组织!`, 'warning');
            }
            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加销售订单分录信息!`, 'warning');
            }
            savetips();
        })

        // 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {

                            // 过滤
                            let _entries = [], _pig = [];
                            $.each(getEntryInfo, function (i, p) {
                                _entries.push(p.entries);
                                $.each(p.breedPigEntries, function (q, w) {
                                    _pig.push(w);
                                });
                            });
                            let datas = _entries.filter(item => item.seq != seq);
                            let pig = _pig.filter(item => item.seq != seq);

                            // 重置seq
                            let _data = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []
                            let _breed = pig.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []
                            let arry = {
                                entries: _data,
                                breedPigEntries: _breed
                            }
                            // 赋值 SessionStorage
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", arry))
                            $('#salesEntry').empty().append(addsaleTemplate(_data));

                            $.closeModal();
                        }
                    }
                ]
            });
        });

        // 编辑
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            // let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0;
            let index = $(this).data('index')
            location.href = `../deliverbills/entry.html?v=${Utils.GetTime()}&orgId=${_vm.saleOrgId}&index=${index}&isEdit=${true}`;
        });
    }

    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >是否确认保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        let ids = Utils.GetSessionStorage("ids");
                        let _entries = [], _breedPigEntries = [];
                        let info = JSON.parse(Utils.GetSessionStorage("getEntryInfo"));
                        // $.each(info, function (z, x) {
                        //     _entries.push(x.entries);
                        //     $.each(x.breedPigEntries, function (q, w) {
                        //         _breedPigEntries.push(w);
                        //     });
                        // });
                        // if (_breedPigEntries.length != 15) {
                        //     return $.toptip('耳号数量必须大于15个。', 'warning');
                        // }
                        if (Utils.IsNotNull(ids)) {
                            let datas = {
                                "bizDate": _vm.bizDate,
                                "saleOrgId": _vm.saleOrgId,
                                "saleOrgName": $(`#saleOrgId`).select2('data')[0].name,
                                "pigType": _vm.pigType,
                                "remark": _vm.remark,
                                "entries": info.entries,
                                "breedPigEntries": info.breedPigEntries
                            }

                            return DeliverApi.upDeliverList(ids, JSON.stringify(datas)).then(res => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示 
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `../deliverbills/deliverbills.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            })

                        }
                        let datas = {
                            "bizDate": _vm.bizDate,
                            "saleOrgId": _vm.saleOrgId,
                            "saleOrgName": $(`#saleOrgId`).select2('data')[0].name,
                            "pigType": _vm.pigType,
                            "remark": _vm.remark,
                            "entries": info.entries,
                            "breedPigEntries": info.breedPigEntries
                        }

                        DeliverApi.addDeliverList(JSON.stringify(datas)).then(res => {
                            $.toptip('请求成功。', 'success');
                            // 延时一秒跳转  要看提示 
                            setTimeout(function () {
                                window.sessionStorage.removeItem("getEntryInfo");
                                window.sessionStorage.removeItem("deliverDatas");
                                location.href = `../deliverbills/deliverbills.html?v=${Utils.GetTime()} `;
                            }, 1000);
                        });
                    }
                }
            ]
        });
    }

    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

})(window, document, jQuery)